if (window.plus) {
    ready();
} else {
    document.addEventListener('plusready', ready, false);
}

$(function () {
    if (AGENT_CLIENT.WEB) {
        ready();
    }
})

function ready() {
    var
		thisPage = {},
		user = {},
		incomeQueryData = {
		    index: 1,
		    size: 5,
		    query: "",
		    search: {},
		    sorting: {}
		},
		filingQueryData = {
		    index: 1,
		    size: 5,
		    query: "",
		    search: {},
		    sorting: {}
		},
		applyQueryData = {
		    index: 1,
		    size: 5,
		    query: "",
		    search: {},
		    sorting: {}
		},
		shareQueryData = {
		    index: 1,
		    size: 5,
		    query: "",
		    search: {},
		    sorting: {}
		},
		html = [];
    html = [];

    var incomePage = function () {
        this.init();
    };
    incomePage.prototype = {
        init: function () {
            this.initData();
            this.bindEvent();
        },
        initData: function () {
            var thisModel = this;
            user = getLocalStorage(STORAGE_MANAGER.user);
            if (!user) {
                redirect("../account/login.html");
                return;
            }
            $.showWaiting();
            $.when(
				//1我的收入
				$.ajax({
				    type: "POST",
				    url: CONFIG_MANAGER.RequstUrl + "v1/settled/myincome/" + user.id,
				    async: true,
				    contentType: 'application/json',
				    data: JSON.stringify(incomeQueryData),
				    headers: { token: user.token }
				}),
				//2商家报备
				$.ajax({
				    type: "POST",
				    url: CONFIG_MANAGER.RequstUrl + "v1/settled/" + user.id + "/10/-1/9",
				    async: true,
				    data: JSON.stringify(filingQueryData),
				    headers: { token: user.token }
				}),
				//3商家签约
				$.ajax({
				    type: "POST",
				    url: CONFIG_MANAGER.RequstUrl + "v1/settled/" + user.id + "/1/-1/9",
				    async: true,
				    contentType: 'application/json',
				    data: JSON.stringify(applyQueryData),
				    headers: { token: user.token }
				}),
				//4惠赚钱
				$.ajax({
				    type: "POST",
				    url: CONFIG_MANAGER.RequstUrl + "v1/member/share/sharelistbytime/" + user.id,
				    async: true,
				    contentType: 'application/json',
				    data: JSON.stringify(shareQueryData),
				    headers: { token: user.token }
				})
			).done(function (incomeData, filingData, signData, shareData) {
			    thisModel.loadPage(incomeData, filingData, signData, shareData);
			}).always(function () {
			    $.closeWaiting();
			});
        },
        loadPage: function (incomeData, filingData, signData, shareData) {
            var income = JSON.parse(incomeData[0]);
            income = income.data;
            var filing = JSON.parse(filingData[0]);
            filing = filing.data;
            var sign = JSON.parse(signData[0]);
            sign = sign.data;
            var share = JSON.parse(shareData[0]);
            share = share.data;
            //income = [];
            var count = 3;
            if (income.length > 0) {
                this.loadMyincome(income);
            }
            if (count > 0) {
                var width = ((parseFloat(1 / count)) * 100).toString() + '%';
                var styleString = '';
                if (income.length == 0) {
                    styleString = 'style="margin-top: 0px;"';
                }
                html.push('<div class="wdsrbtk mbbottom" ' + styleString + ' id="ul_tab">');
                html.push('<ul>');
                styleString = 'style="width:' + width + '"';
                html.push('<li tip="filing" class="hover" ' + styleString + '>商家报备</li>');
                html.push('<li tip="apply" ' + styleString + '>商家签约</li>');
                html.push('<li tip="earning" ' + styleString + '>惠赚钱</li>');
                html.push('</ul>');
                html.push('<p id="colorline" class="xhx xhx2" ' + styleString + '></p>');
                html.push('</div>');
                //连续拼接html
                this.loadFilings(filing);
                this.loadFilingDetails(sign);
                this.loadShares(share);
            }
            $("#main").html(html.join(''));
        },
        //我的收入
        loadMyincome: function (income) {
            var i = 0;
            while (income[i]) {
                html.push('<div class="yqjlk mbbottom">');
                html.push('<div class="ygjlbg">');
                html.push('<p class="yqzccg">'+ getincomeType(income[i].source_type) +'</p>');
                html.push('<p class="yqhyny"><span>&yen;' + income[i].gain + '</span>来源：' + income[i].source + '</p>');
                html.push('<p class="yqhyny yqhyny1"><span>' + getRewardMoneyType(income[i].money_type) + '</span>' + toDateString(income[i].create_time, 'yyyy-MM-dd hh:mm:ss') + '</p>');
                html.push('</div>');
                html.push('</div>');
                i++;
            }
            html.push('<p id="checkMore" class="djckgd mbbottom">点击查看更多</p>');
        },
        //商家报备
        loadFilings: function (filings) {
            var thisModel = this;
            if (filings.length > 0) {

                html.push('<div name="filing" id="filingDetail">');
                $.each(filings, function (i, item) {
                    //详情
                    html.push('<div class="navbg mbtopbottom">');
                    html.push('<p class="kfsp">' + item.name + '</p>');
                    html.push('<ul class="sqliucheng">');

                    //已提交
                    html.push('<li class="lctb lctb-hover"><i class="iconfont icon-dingDanYiTiJiao"></i><br>已提交</li>');
                    html.push('<li class="lcjiantou lctb-hover"><i class="iconfont icon-arrow"></i></li>');

                    //洽谈中
                    html.push('<li class="lctb ' + ((item.status >= 1) ? 'lctb-hover' : '') + '"><i class="iconfont icon-duihua2"></i><br>洽谈中</li>')
                    html.push('<li class="lcjiantou ' + ((item.status >= 1) ? 'lctb-hover' : '') + '"><i class="iconfont icon-arrow"></i></li>');

                    //资料审核
                    html.push('<li class="lctb ' + ((item.status >= 2 && !thisModel.cancelOrRefuse(item.status)) ? 'lctb-hover' : '') + '"><i class="iconfont icon-jianlisousuo"></i><br>资料审核</li>');
                    html.push('<li class="lcjiantou ' + ((item.status >= 2 && !thisModel.cancelOrRefuse(item.status)) ? 'lctb-hover' : '') + '"><i class="iconfont icon-arrow"></i></li>');

                    //签约中
                    html.push('<li class="lctb ' + ((item.status >= 5 && !thisModel.cancelOrRefuse(item.status) && !thisModel.cancelOrNoAudit(item.audit_status)) ? 'lctb-hover' : '') + '"><i class="iconfont icon-14tijiaochuangyibuzouer"></i><br>签约中</li>');
                    html.push('<li class="lcjiantou ' + ((item.status >= 5 && !thisModel.cancelOrRefuse(item.status) && !thisModel.cancelOrNoAudit(item.audit_status)) ? 'lctb-hover' : '') + '"><i class="iconfont icon-arrow"></i></li>');

                    //已返现
                    html.push('<li class="lctb ' + ((item.status == 11) ? 'lctb-hover' : '') + '"><i class="iconfont icon-wiappquxianguanli"></i><br>已返现</li>');

                    html.push('</ul>');
                    html.push('<div class="wlgzxxny wdsrsjbb">');

                    //审核步骤
                    if (item.list_log && item.list_log.length > 0) {
                        //						if([2].indexOf(item.audit_status) > -1){
                        //							thisModel.mergeLog(item);
                        //						}
                        $.each(item.list_log, function (i, log) {
                            html.push('<div class="wlxx ' + ((i == 0) ? 'wlxx1' : '') + '">');
                            if (i == 0) {
                                var status = { status: item.status, audit_status: item.audit_status };
                                html.push('<input type="hidden" value=' + JSON.stringify(status) + '/>')
                            }
                            html.push('<p class="wlxxlc mbbottom"><b class="dwyuan ' + ((i == 0) ? (thisModel.cancelOrRefuse(item.status) ? 'dwyuan2' : (thisModel.barandNoAudit(log.origin, log.changed) ? 'dwyuan3' : 'dwyuan1')) : '') + '"></b>' + log.result);
                            html.push('<br><span>' + toDateString(log.create_time, 'yyyy-MM-dd hh:mm:ss') + '</b></span></p>');
                            html.push('</div>');
                        });
                    }
                    html.push('</div>');
                    html.push('</div>');
                });
                html.push('</div>');
            } else {
                html.push('<div name="filing" id="filingDetail" class="zhanwushuju"><img src="../../images/zanwushuju.png"><br>暂无数据</div>');
            }
        },
        //判断是否拒绝或者取消
        cancelOrRefuse: function (status) {
            return ([8, 9].indexOf(status) > -1);
        },
        //判断是否不通过审核或取消
        cancelOrNoAudit: function (audit_status) {
            return ([2].indexOf(audit_status) > -1);
        },
        //判断是否品牌不通过
        barandNoAudit: function (orgin, changed) {
            return (orgin == 3 && changed == 3);
        },
        mergeLog: function (item) {
            var mergedLog = [];
            var i = 0;
            var index = 0;
            while (item.list_log[i]) {
                if ((item.list_log[i].origin == 3) && (item.list_log[i].changed == 5)) {
                    if (i == 0) {
                        item.halfAudit = true;
                        mergedLog.push(item.list_log[i]);
                    } else {
                        index = mergedLog.length - 1;
                        mergedLog[index].result += ('</br>' + item.list_log[i].result);
                    }
                    i++;
                    continue;
                } else {
                    mergedLog.push(item.list_log[i]);
                }
                i++;
            }
            item.list_log = mergedLog;
            return item;
        },
        //商家签约
        loadFilingDetails: function (sign) {
            var thisModel = this;
            if (sign.length > 0) {
                html.push('<div name="apply" style="display:none" id="signDetail">');
                $.each(sign, function (i, item) {
                    var changed = item.list_log[0].changed;
                    html.push('<div class="navbg mbtopbottom">');
                    html.push('<p class="kfsp">' + item.name + '</p>');

                    //图示
                    html.push('<ul class="sqliucheng sqliucheng2" style="margin: 10px 10%;">');
                    //已提交
                    html.push('<li class="lctb lctb-hover"><i class="iconfont icon-dingDanYiTiJiao"></i><br>已提交</li>');
                    html.push('<li class="lcjiantou lctb-hover"><i class="iconfont icon-arrow"></i></li>');
                    //资料审核
                    html.push('<li class="lctb ' + ((item.status >= 2 && !thisModel.cancelOrRefuse(item.status)) ? 'lctb-hover' : '') + '"><i class="iconfont icon-jianlisousuo"></i><br>资料审核</li>');
                    html.push('<li class="lcjiantou ' + ((item.status >= 2) ? 'lctb-hover' : '') + '"><i class="iconfont icon-arrow"></i></li>');
                    //已返现
                    html.push('<li class="lctb ' + ((item.status >= 11 && !thisModel.cancelOrRefuse(item.status)) ? 'lctb-hover' : '') + '"><i class="iconfont icon-wiappquxianguanli"></i><br>已返现</li>');
                    html.push('</ul>');

                    html.push('<div class="wlgzxxny wdsrsjbb">');
                    if (item.list_log && item.list_log.length > 0) {
                        //thisModel.mergeLog(item);
                        $.each(item.list_log, function (i, log) {
                            html.push('<div class="wlxx ' + ((i == 0) ? 'wlxx1' : 'wlxx') + '">');
                            html.push('<p class="wlxxlc mbbottom"><b class="dwyuan ' + ((i == 0) ? (thisModel.cancelOrRefuse(item.status) ? 'dwyuan2' : (thisModel.barandNoAudit(log.origin, log.changed) ? 'dwyuan3' : 'dwyuan1')) : '') + '"></b>' + log.result);
                            html.push('<br><span>' + toDateString(log.create_time, 'yyyy-MM-dd hh:mm:ss') + '</b></span></p>');
                            html.push('</div>');
                        });
                    }
                    html.push('</div>');
                    html.push('</div>');
                });
                html.push('</div>');
            } else {
                html.push('<div name="apply" id="signDetail" style="display:none"  class="zhanwushuju"><img src="../../images/zanwushuju.png"><br>暂无数据</div>');
            }
        },
        //惠赚钱
        loadShares: function (shares) {
            if (shares.length > 0) {
                html.push('<div name="earning" style="display:none" id="earingList">');
                $.each(shares, function (i, item) {
                    html.push('<div class="sjbbny">');
                    html.push('<div class="ddnybbt mbbottom">');
                    html.push('<p class="dfktbdw">购买成功</p>');
                    html.push('<dl class="cpxqxztop cpxqxztop1 mtop0">');
                    html.push('<dt><img src="' + getImageUrl(item.sku_logo, 65, 66) + '"></dt>');
                    html.push('<dd class="shenglh">' + item.sku_name + '</dd>');
                    if (item.link_list && item.link_list.length > 0) {
                        html.push('<dd class="huisezi mtop10">' + toDateString(item.link_list[0].buy_date, 'yyyy-MM-dd hh:mm:ss') + '</dd>');
                    }
                    html.push('</dl>');
                    html.push('</div>');
                    if (item.link_list && item.link_list.length > 0) {
                        html.push('<div class="syhgdbg mbbottom">');
                        //未知状态显示
                        var src = (item.link_list[0].status == 0) ? "../../images/sskbz1.png" : "../../images/sskbz.png";
                        html.push('<p class="sskbz mbright"><img src="' + src + '"></p>');
                        html.push('<ul class="syhg">');
                        html.push('<li><a href="javascript:void(0);">' + item.link_list[0].status_text + '</a></li>');
                        html.push('</ul>');
                        html.push('</div>');
                    }
                    html.push('</div>');
                });
                html.push('</div>');
            } else {
                html.push('<div name="earning" id="earingList" style="display:none" class="zhanwushuju"><img src="../../images/zanwushuju.png"><br>暂无数据</div>');
            }
        },
        bindEvent: function () {
            //点击回退
            $("#back").on("click", function () {
                if (AGENT_CLIENT.APP) {
                    plus.webview.getWebviewById("../home/main.html").evalJS("redirectTab(4)");
                } else {
                    redirect('../mine/mylife.html');
                }
            });

            //商家报备，商家签约，惠赚钱切换
            $("#main").on("click", "#ul_tab li", function () {
                var tip = $(this).attr("tip");
                $(this).addClass("hover").siblings().removeClass("hover");
                var value = "translateX(" + $(this).offset().left + "px)";
                $("#colorline").css({
                    "transform": value,
                    "-moz-transform": value,
                    "-webkit-transform": value,
                    "-o-transform": value,
                    "-ms-transform": value
                });
                //加载
                $("#ul_tab").nextAll().hide();
                $("div[name='" + tip + "']").show();
            });

            //点击查看更多
            $("#main").on("click", "#checkMore", function () {
                incomeQueryData.index++;
                $.ajax({
                    type: "POST",
                    url: CONFIG_MANAGER.RequstUrl + "v1/settled/myincome/" + user.id,
                    async: true,
                    contentType: 'application/json',
                    data: JSON.stringify(incomeQueryData),
                    headers: { token: user.token }
                }).done(function (data) {
                    data = JSON.parse(data);
                    var filings = data.data;
                    if (filings.length > 0) {
                        html = [];
                        $.each(filings, function (i, item) {
                            //列表
                            html.push('<div class="yqjlk mbbottom">');
                            html.push('<div class="ygjlbg">');
                            html.push('<p class="yqzccg">商家报备</p>');
                            html.push('<p class="yqhyny"><span>&yen;' + item.gain + '</span>来源：' + item.source + '</p>');
                            html.push('<p class="yqhyny yqhyny1"><span>' + item.status_text + '</span>' + toDateString(item.create_time, 'yyyy-MM-dd hh:mm:ss') + '</p>');
                            html.push('</div>');
                            html.push('</div>');
                        });
                        $(html.join('')).insertBefore($("#checkMore"));
                    } else {
                        $.toast("没有更多");
                    }
                }).always(function (data) {

                }).fail(function (data) {
                    var infor = JSON.parse(data);
                    $.toast(infor);
                });
            });



        }
    };

    thisPage = new incomePage();
}